package com.xike.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.act.LoginAct;
import com.common.Constant;
import com.control.UserControl;
import com.loopj.android.http.RequestParams;
import com.xike.imageloader.core.DisplayImageOptions;
import com.xike.imageloader.core.ImageLoader;
import com.xike.imageloader.core.assist.FailReason;
import com.xike.imageloader.core.listener.ImageLoadingListener;

public class MyUtil {
	/**
	 * @description:判定手机号
	 * @param phoneNumber
	 * @return
	 */

	public static boolean isPhoneNumberValid(String phoneNumber) {
		// boolean isValid = false;
		// /**
		// * 可接受的电话格式有:
		// * ^//(? : 可以使用 "(" 作为开头
		// * (//d{3}): 紧接着三个数字
		// * //)? : 可以使用")"接续
		// * [- ]? : 在上述格式后可以使用具选择性的 "-".
		// * (//d{3}) : 再紧接着三个数字
		// * [- ]? : 可以使用具选择性的 "-" 接续.
		// * (//d{5})$: 以五个数字结束.
		// 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、182、183、187、188
		// 联通：130、131、132、152、155、156、185、186
		// 电信：133、153、180、189、（1349卫通）
		if (!StringUtil.isNotNull(phoneNumber)) {
			return false;
		}
		if (phoneNumber.length() != 11) {
			return false;
		}
		return true;
		// Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
		// Matcher m = p.matcher(phoneNumber);
		// return m.matches();
	}

	/**
	 * @description: 手机号码中间4位加密
	 * @user wzl email:wzl200711402@163.com
	 * @date 2014-2-13
	 * @return
	 */
	public static String encryptPhoneNum(String phoneNum) {
		if (!isPhoneNumberValid(phoneNum)) {
			return "无法识别";
		}
		StringBuffer sb = new StringBuffer();
		sb.append(phoneNum.substring(0, 3));
		sb.append("****");
		sb.append(phoneNum.substring(7));
		return sb.toString();

	}

	public static String getEditTextContent(EditText edt) {
		return edt != null ? edt.getText().toString().toString() : "";
	}

	public static void setTextViewText(TextView tv, String content, int type, String defualt) {
		if (tv == null) {
			return;
		}
		if (StringUtil.isNotNull(content)) {
			tv.setText(content);
			tv.setVisibility(View.VISIBLE);
		} else {
			if (StringUtil.isNotNull(defualt)) {
				tv.setText(defualt);
				tv.setVisibility(View.VISIBLE);
			} else {
				tv.setVisibility(type);
			}
		}
	}

	/**
	 * @description:TODO拨打电话
	 * @FileName MyUtil.java
	 * @params @param context
	 * @params @param telNums
	 * @return void
	 * @user wzl email:wzl200711402@163.com
	 * @date 2013-5-21
	 */
	public static void intentToPhone(final Context context, String telNums) {
		if (telNums == null || telNums.equals("")) {
			return;
		}
		if (telNums.contains("/")) {
			telNums = telNums.substring(0, telNums.indexOf("/"));
		}
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_DIAL);
		intent.setData(Uri.parse("tel:" + telNums));
		context.startActivity(intent);

	}

	/**
	 * @description:给listview设置固定高度，但是需要注意父布局LinearLayout.LayoutParams
	 * @user wzl email:wzl200711402@163.com
	 * @date 2013-9-13
	 */
	public static void setListViewHeightBasedOnChildren(ListView listView) {
		// 获取ListView对应的Adapter
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}

		int totalHeight = 0;
		for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0); // 计算子项View 的宽高
			totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
		}

		LinearLayout.LayoutParams params = (LayoutParams) listView.getLayoutParams();
		params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		// listView.getDividerHeight()获取子项间分隔符占用的高度
		// params.height最后得到整个ListView完整显示需要的高度
		listView.setLayoutParams(params);
	}

	/**
	 * @param context
	 * @return 检查网络是否可用
	 */
	public static boolean netIsConnect(Context context) {
		// 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
		try {
			ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				// 获取网络连接管理的对象
				NetworkInfo info = connectivity.getActiveNetworkInfo();
				if (info != null && info.isConnected()) {
					// 判断当前网络是否已经连接
					if (info.getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				} else {
					return false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static int getAppVersionCode(Context context) {// 获得当前版本号
		try {
			return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return 99;
		}
	}

	// 将图片的四角圆化
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
		if (bitmap == null || bitmap.getWidth() == 0) {
			return null;
		}
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
		// 得到画布
		Canvas canvas = new Canvas(output);

		// 将画布的四角圆化
		final int color = Color.RED;
		final Paint paint = new Paint();
		// 得到与图像相同大小的区域 由构造的四个值决定区域的位置以及大小
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		// 值越大角度越明显
		final float roundPx = 15;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		// drawRoundRect的第2,3个参数一样则画的是正圆的一角，如果数值不同则是椭圆的一角
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		return output;
	}

	public static DisplayImageOptions getCommonImageOptions() {
		return new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true).build();
	}

	/**
	 * @description: 获得默认图大小的圆角图片
	 * @user wzl email:wzl200711402@163.com
	 * @date 2014-2-28
	 * @param defaultbitmap
	 * @param bitmap
	 * @return
	 */
	public static Bitmap getRoundCornerBitmap(Context context, Bitmap defaultbitmap, Bitmap bitmap) {
		if (defaultbitmap == null || defaultbitmap.getWidth() == 0) {
			MLog.w("getRoundCornerBitmap", "defaultbitmap is null");
			return null;
		}
		int w = defaultbitmap.getWidth();
		int h = defaultbitmap.getHeight();
		if (bitmap == null || bitmap.getWidth() == 0) {
			bitmap = defaultbitmap;
		}
		Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		float densityMultiplier = context.getResources().getDisplayMetrics().density;
		int color = 0xff424242;
		Paint paint = new Paint();
		Rect rect = new Rect(0, 0, w, h);
		RectF rectF = new RectF(rect);
		// make sure that our rounded corner is scaled appropriately
		float roundPx = 6 * densityMultiplier;
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		// draw rectangles over the corners we want to be square
		// canvas.drawRect(0, 0, w / 2, h / 2, paint);
		// canvas.drawRect(w / 2, 0, w, h / 2, paint);
		// canvas.drawRect(0, h / 2, w / 2, h, paint);
		// canvas.drawRect(w / 2, h / 2, w, h, paint);

		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		Bitmap resultbitmap = getMyWidthBitmap(bitmap, w, h);
		canvas.drawBitmap(resultbitmap, 0, 0, paint);
		return output;
	}

	public static Bitmap ddddd(Context context, Bitmap bitmap) {
		int w = context.getResources().getDisplayMetrics().widthPixels;
		Log.e("w", "w" + w);
		int h = bitmap.getHeight();
		Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		int color = 0xffffffff;
		Paint paint = new Paint();

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);

		Rect rect = new Rect(0, 0, w, h);
		RectF rectF = new RectF(rect);
		canvas.drawRect(rectF, paint);
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		int left = w - bitmap.getWidth() / 2;
		canvas.drawBitmap(bitmap, left, 0, paint);
		return output;
	}

	public static Bitmap getMyWidthBitmap(Bitmap bitmap, int mwidth, int mheight) {
		if (bitmap == null || bitmap.getWidth() <= 0) {
			return null;
		}
		// 获得图片的宽高
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		// 设置想要的大小
		int newWidth = mwidth;
		int newHeight = mheight;
		// 计算缩放比例
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 取得想要缩放的matrix参数
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		// 得到新的图片
		return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
	}

	public static void displayImageView(final Context context, String url, ImageView imageview, final Bitmap defaultBitmap, final boolean withCorner) {
		imageview.setTag(url);
		ImageLoader.getInstance().displayImage(url, imageview, MyUtil.getCommonImageOptions(), new ImageLoadingListener() {

			@Override
			public void onLoadingStarted(String imageUri, View view) {
				((ImageView) view).setImageBitmap(defaultBitmap);
			}

			@Override
			public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
				if (view != null) {
					((ImageView) view).setImageBitmap(defaultBitmap);
				}
			}

			@Override
			public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
				if (loadedImage != null && loadedImage.getWidth() > 0) {
					if (withCorner) {
						if (defaultBitmap != null && defaultBitmap.getWidth() > 0) {
							loadedImage = MyUtil.getRoundCornerBitmap(context, defaultBitmap, loadedImage);
						}
					}
					String strTag = (String) view.getTag();
					if (strTag.equals(imageUri)) {
						((ImageView) view).setImageBitmap(loadedImage);
					}
				} else {
					((ImageView) view).setImageBitmap(defaultBitmap);
				}
			}

			@Override
			public void onLoadingCancelled(String imageUri, View view) {
				if (view != null) {
					((ImageView) view).setImageBitmap(defaultBitmap);
				}
			}
		});
	}

	public static void intentToLogin(Context context, int requestCode) {
		if (requestCode > 0) {
			((Activity) context).startActivityForResult(new Intent(context, LoginAct.class), requestCode);
		} else {
			context.startActivity(new Intent(context, LoginAct.class));
		}

	}

	/**
	 * @Description: TODO<加密请求参数>
	 * @author: wzl
	 * @data: 2014年9月27日 下午6:22:28
	 */
	public static String signRequestUrl(String mainUrl, ArrayList<BasicNameValuePair> params) {
		StringBuffer sb = new StringBuffer(mainUrl);
		if (mainUrl.indexOf('?') != -1) {
			sb.append('&');
		} else {
			sb.append('?');
		}
		ArrayList<String> alName = new ArrayList<String>();
		HashMap<String, String> maps = new HashMap<String, String>();
		if (params != null) {
			for (BasicNameValuePair nv : params) {
				if (nv != null) {
					if (StringUtil.isNotNull(nv.getValue())) {
						try {
							alName.add(nv.getName());
							maps.put(nv.getName(), nv.getValue());
							sb.append(nv.getName()).append('=').append(URLEncoder.encode(nv.getValue(), "utf-8")).append('&');
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		if (UserControl.isLogined() && !mainUrl.contains(Constant.SERVER_URL_MD5KEY) && !mainUrl.contains(Constant.SERVER_URL_LOGIN)) {
			String strAccess_token = UserControl.getAccessToken();
			alName.add("access_token");
			maps.put("access_token", strAccess_token);
			sb.append("access_token").append('=').append(strAccess_token).append('&');

			String strSignature = StringUtil.MD5(Constant.APPSERRET + UserControl.getAccessTokenSecret());
			alName.add("signature");
			maps.put("signature", strSignature);
			sb.append("signature").append('=').append(strSignature).append('&');
		}

		String strClientInfo = Manager.getClientInfo();
		alName.add("client_info");
		maps.put("client_info", strClientInfo);
		sb.append("client_info").append('=').append(strClientInfo).append('&');

		alName.add("app_key");
		maps.put("app_key", Constant.APPKEY);
		sb.append("app_key").append('=').append(Constant.APPKEY).append('&');

		StringBuffer sbParams = new StringBuffer();
		Collections.sort(alName);
		for (String name : alName) {
			sbParams.append(name).append('=').append(maps.get(name)).append('&');
		}
		// MLog.e("sbParams", ""+sbParams.toString());
		if (sbParams.length() > 1) {
			sbParams.deleteCharAt(sbParams.length() - 1);
		}
		String needMd5Str = sbParams.toString() + Constant.APPSERRET;
		sb.append("sign=").append(StringUtil.MD5(needMd5Str).toUpperCase());
		return sb.toString();
	}

	/**
	 * @Description: TODO <签名需要签名的参数>
	 * @author: wzl
	 * @data: 2014年10月13日 下午4:34:18
	 */
	public static String getSignRequestParams(ArrayList<BasicNameValuePair> params) {
		ArrayList<String> alName = new ArrayList<String>();
		HashMap<String, String> maps = new HashMap<String, String>();
		if (params != null) {
			for (BasicNameValuePair nv : params) {
				if (nv != null) {
					if (StringUtil.isNotNull(nv.getValue())) {
						alName.add(nv.getName());
						maps.put(nv.getName(), nv.getValue());
					}
				}
			}
		}

		StringBuffer sbParams = new StringBuffer();
		Collections.sort(alName);
		for (String name : alName) {
			sbParams.append(name).append('=').append(maps.get(name)).append('&');
		}
		if (sbParams.length() > 1) {
			sbParams.deleteCharAt(sbParams.length() - 1);
		}
		String needMd5Str = sbParams.toString() + Constant.APPSERRET;
		return StringUtil.MD5(needMd5Str).toUpperCase();
	}

	/**
	 * @Description: TODO<post请求时，获得请求参数>
	 * @author: wzl
	 * @data: 2014年10月22日 上午11:23:05
	 */
	public static RequestParams getPostRequestParams(ArrayList<BasicNameValuePair> params) {
		if (UserControl.isLogined()) {
			String strSignature = StringUtil.MD5(Constant.APPSERRET + UserControl.getAccessTokenSecret());
			params.add(new BasicNameValuePair("access_token", UserControl.getAccessToken()));
			params.add(new BasicNameValuePair("signature", strSignature));
		}

		params.add(new BasicNameValuePair("app_key", Constant.APPKEY));
		params.add(new BasicNameValuePair("client_info", Manager.getClientInfo()));

		RequestParams requestParams = new RequestParams();
		for (BasicNameValuePair bnvp : params) {
			try {
				requestParams.add(bnvp.getName(), URLEncoder.encode(bnvp.getValue(), "utf-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		requestParams.put("sign", getSignRequestParams(params));
		return requestParams;
	}
}
